const User = require('../models/User');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// 登录控制器
exports.login = async (req, res) => {
  const { account, password } = req.body;

  try {
    // 查找用户
    const user = await User.findOne({ account });

    if (!user) {
      return res.status(200).json({ errCode: 1003, errMsg: '账号不存在' });
    }

    // 验证密码
    const isMatch = await user.matchPassword(password);

    if (!isMatch) {
      return res.status(200).json({ errCode: 1004, errMsg: '密码错误' });
    }

    // 生成token
    const token = jwt.sign(
      { id: user._id },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN }
    );

    res.json({
      errCode: 0,
      errMsg: 'success',
      data: {
        token,
        username: user.username,
        account: user.account,
        avatar: user.avatar,
        email: user.email,
        phone: user.phone,
        role: user.role,
        _id: user._id
      }
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ errCode: 500, errMsg: '服务器错误' });
  }
};